package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"register/models"
)

type HospitalController struct {
	beego.Controller
}

func (c *HospitalController) Register() {
	hospital_name := c.GetString("hospital_name")
	address := c.GetString("address")
	name := c.GetString("name")
	cate := c.GetString("cate")
	price, _ := c.GetFloat("price")
	room_address := c.GetString("room_address")

	if hospital_name == "" || address == "" || name == "" || cate == "" || price <= 0 || room_address == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "预约医院信息不能为空",
		}
		c.ServeJSON()
		return
	}

	var hospital models.Hospital
	hospital.HospitalName = hospital_name
	hospital.Address = address
	hospital.Name = name
	hospital.Cate = cate
	hospital.Price = price
	hospital.RoomAddress = room_address

	err := hospital.Creates()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "预约医院失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mag":  "预约医院成功",
	}
	c.ServeJSON()
}
func (c *HospitalController) Lists() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 5)

	var count int64
	models.DB.Model(&models.Hospital{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(pageSize)))
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > sum {
		down = sum
	}

	var hospital models.Hospital
	hospitals, err := hospital.List(page, pageSize)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "查询失败",
		}
		c.ServeJSON()
		return
	}

	pageData := map[string]interface{}{
		"sum":  sum,
		"up":   up,
		"down": down,
		"data": hospitals,
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mag":  "查询成功",
		"data": pageData,
	}
	c.ServeJSON()
}
